<template>
  <div class="editForm-wrapper">
    <!-- 物流伙伴编辑dialog-->
    <el-dialog :title="title" :close-on-click-modal="false" v-dialogDrag :visible.sync="editVisible">
      <el-form label-width="127px" :rules="dataRule" ref="editForm" :model="editForm" v-loading="getPhoneLoading||sendMsgLoading">
        <el-form-item label="物流伙伴名称:" prop="names" :rules="[
                              {required: true, message:'请输入物流伙伴名称', trigger:'change'}
                             ]">
          <el-autocomplete clearable placeholder="请输入物流伙伴名称" size="small" @blur.stop="saveLocal($event.target.value)"  :debounce="0" :fetch-suggestions="companySearch"   @select="handleSelect($event)" :trigger-on-focus="true" v-model="editForm.names"
          >
            <template slot-scope="{ item }">

              <section class="querySearch-autocomplete">
                <section class="name-item">
                  <section class="name"><span v-if="item.names">{{ item.names.substr(0,1) }}</span></section>
                  {{ item.names}}
                </section>
              </section>

              <div></div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="手机号:" prop="contactPhone">
          <el-input clearable  v-model="editForm.contactPhone" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="验证码:" prop="captcha">
<!--          {{letTimes.nowTime}}-->
          <el-input :clearable="false"  v-model="editForm.captcha">
            <el-button type="text" v-if="chenckMsg === '1'" class="primary" slot="suffix" @click="getCaptcha(0)" >获取验证码</el-button>
            <el-button type="text" v-if="chenckMsg === '2'" class="info" slot="suffix" disabled>已发送</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary"  @click="doSubmit" v-noMoreClick >确定</el-button>
        <el-button size="small" @click="close()" :disabled="submitLoading">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {companySearch} from '@/api/market/crm.js'
import {
	getPhoneByCompanyId,
	sendCaptcha,
	saveCompany,
	verifyCompany
} from '@/api/secondCarrier/crm.js'
  export default {
    components: {},
    data () {
    	let captchaRequired=(rule,value,callback)=>{
    		if(this.method=='verify'&&!value){
    			callback(new Error(rule.message))
    		}else{
    			callback()
    		}
    	}
      return {
      	getPhoneLoading:false,
      	sendMsgLoading:false,
      	submitLoading:false,
      	editForm: {
      	  names: '',
      	  companyId: '',
      	  contactPhone: '',
      	  captcha: '',
      	  props: 3
      	},
      	dataRule: {
      	  names: [{
      	    required: true,
      	    message: '请输入物流伙伴名称',
      	    trigger: 'blur'
      	  }],
      	  contactPhone: [{
      	    required: true,
      	    message: '手机号不能为空',
      	    trigger: 'change'
      	  }],
//    	  captcha: [{
//    	    required: false,
//    	    message: '请输入验证码',
//    	    trigger: 'blur'
//    	  }]
      	  captcha: [{
      	    validator:captchaRequired,
      	    message: '请输入验证码',
      	    trigger: 'blur'
      	  }]
      	},
      	method: '',
      	title: '',
      	chenckMsg: '1',
      	
      	
        letTimes: { nowTime: '' },
        viewForm: {
          types: '',
          names: '',
          codes: '',
          idCard: '',
          contactName: '',
          contactPhone: '',
          id: ''
        },
        editVisible: false,
        detailsVisible: false,
      }
    },
    methods: {
      init(method, editForm) {
      	this.method = method
        if (method === 'add') {
        	this.editVisible = true
          this.chenckMsg = '1'
          this.$nextTick(() => {
            this.$refs.editForm.resetFields()
          })
          this.title = '新增物流伙伴'
//      } else if (method === 'edit') {
//    		this.editVisible = true
//        this.$nextTick(() => {
//          this.$refs.editForm.resetFields()
//          this.editForm = editForm
//        })
//        this.title = '编辑物流伙伴'
//      } else if (method === 'view') {
//        this.viewForm = editForm
//        this.detailsVisible = true
//        this.title = '物流伙伴详情'
        }else if(method=='verify'){
      		this.editVisible = true
          this.$nextTick(() => {
            this.$refs.editForm.resetFields()
            this.editForm = editForm
          })
        }
      },
      saveLocal (val) {
      },
      // 输入后匹配输入建议
      companySearch (queryString, cb) {
        // if (queryString) {
        companySearch({
          pageNo: 1,
					pageSize: 10,
					fullNames: queryString
        }).then((res) => {
          if (res.data.code === '200') {
            this.values = [];
            let list=res.data.result||[]
            for (let index = 0; index < list.length; index++) {
              const elementCompany = {
                names: list[index].fullName,
                companyId: list[index].companyId,
								companySn: list[index].companySn
              }
              this.values.push(elementCompany)
            }
            cb(this.values)
          }
        })
        if (!queryString) {
          this.editForm.contactPhone = ''
        }
        // }
      },
      handleSelect ($event) {
        this.editForm.names = $event.names
        this.editForm.companyId = $event.companyId
        this.editForm.companySn = $event.companySn
        this.getContactPhone()
//      this.getSmsMsg($event.contactPhone)
      },
      //获取企业手机号
      getContactPhone(){
      	let companyId=this.editForm.companyId;
      	if(!companyId){
      		return;
      	}
      	this.getPhoneLoading=true;
      	getPhoneByCompanyId({id:companyId}).then(res=>{
      		this.getPhoneLoading=false;
      		if (res.data.code === '200') {
            let result=res.data.result||{}
            this.$set(this.editForm,'contactPhone',result.contactPhone)
          }
      	})
      },
      getCaptcha (type) {
      	if(this.sendMsgLoading){
      		return;
      	}
      	this.sendMsgLoading=true;
        sendCaptcha({
          contactPhone: this.editForm.contactPhone,
          captchaTemplate: type,
          source: 3
        }).then((res) => {
      		this.sendMsgLoading=false;
          if (res.data.code === '200') {
            this.$message({
              message: '短信发送成功',
              type: 'success'
            })
          }
        })
      },
      close() {
        this.editVisible = false
      },
      doSubmit() {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
          	this.submitLoading=true;
          	let form=this.editForm,
          	params={
          		companyId:form.companyId,
          		contactPhone:form.contactPhone,
          		companySn:form.companySn,
          		captcha:form.captcha,
          	}
          	if(this.method=='verify'){
          		//验证物流伙伴
          		verifyCompany(params).then((res) => {
	          		this.submitLoading=false;
	              if (res.data.code === '200') {
	                this.$message({
	                  message: '验证成功',
	                  type: 'success'
	                })
	                this.editVisible = false
	                this.$emit('refreshDataList')
	              }
	            })
          		return;
          	}
            saveCompany(params).then((res) => {
          		this.submitLoading=false;
              if (res.data.code === '200') {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.editVisible = false
                this.$emit('refreshDataList')
              }
            })
          }
        })
      },
      // 选择客户类型
      changeHandlerType(e) {
        this.editForm.types = e
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      // 身份证重复
      checkRepeatIdCard(rule, value, callback) {
        if (value && (!(/\d{17}[\d|x]|\d{15}/).test(value) || (value.length !== 15 && value.length !== 18))) {
          callback(new Error('身份证号码不符合规范'))
        }
        if (value) {
          checkRepeat({
            id: this.editForm.id,
            idCard: value
          }).then(res => {
            if (res.data.code === '200') {
              callback()
            } else {
              callback(new Error('客户身份证有重复'))
            }
          })
        } else {
          callback()
        }
      },
      // 社会统一代码重复
      checkRepeatCode(rule, value, callback) {
        if (this.method === 'edit') {
          return callback()
        }
        if (value) {
          checkRepeat({
            id: this.editForm.id,
            codes: value
          }).then(res => {
            if (res.data.code !== '200') {
              callback(new Error('信用代码有重复'))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      },
      checkRepeatName(rule, value, callback) {
        if (this.method === 'edit') {
          return callback()
        }
        if (value) {
          checkRepeat({
            id: this.editForm.id,
            names: value
          }).then(res => {
            if (res.data.code !== '200') {
              callback(new Error('名称有重复'))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      }
    },
    mounted() {
    }
  }
</script>
<style lang="scss" scoped>
  @import '@/assets/scss/config.scss';
  ::v-deep .el-input--suffix{
    .el-input__inner{
      padding-right: 100px !important;
    }
    .el-input__suffix{
      right: 0;
      .el-input__inner{
        padding-right: 100px;
      }
      .primary{
        color: $--color-primary-liyu;
      }
      .el-button{
        position: relative;
        top: -1px;
        right: -1px;
      }
    }
  }
  .view-container {
    .label-container {
      width: 150px;
      /*font-size: 16px;*/
      /*font-weight: 400;*/
      /*color: #666666;*/
    }
    .queryCompanySearch{
      color: #999999;
      margin-bottom: 5px;
      .name-item{
        display: flex;
      }
      .name{
        width: 28px;
        height: 28px;
        text-align: center;
        background: #EEEEEE;
        line-height: 28px;
        border-radius: 28px;
        margin-right: 5px;
      }

    }

    /*.form-container {*/
    /*  font-size: 14px;*/
    /*  font-weight: 400;*/
    /*  color: #333333;*/
    /*  width: 200px;*/
    /*}*/
  }
</style>
